package com.douyang.utils;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.douyang.base.model.UserBaseInfo;
import com.douyang.base.utils.UserUtil;
import com.douyang.dto.DeepSeekDTO;
import com.douyang.pojo.DeepSeekMessage;
import com.douyang.pojo.Message;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;

@Component
public class FluxFactory {

    @Value("${deepseek.apiKey}")
    private String apiKey;

    @Autowired
    private WebClient webClient;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    public Flux<String> flux(List<DeepSeekMessage> systemList,String model) {
        if(systemList==null)systemList=List.of();

        UserBaseInfo loginUserBaseInfo = UserUtil.getLoginUserBaseInfo();
        List<Object> messageListObject = redisTemplate.opsForList().range("message_list:" + loginUserBaseInfo.getId(), 0, -1);
        List<DeepSeekMessage>userList=new ArrayList<>();
        if(!CollectionUtils.isEmpty(messageListObject)){
            userList = messageListObject.stream().map(messageObject -> {
                Message message = new Message();
                BeanUtils.copyProperties(messageObject, message);
                return DeepSeekMessage.builder()
                        .content(message.getMessage())
                        .role(message.getSystem() ? "assistant" : "user")
                        .build();
            }).toList();

        }

        systemList.addAll(userList);

        DeepSeekDTO build = DeepSeekDTO.builder()
                .stream(true)
                .messages(systemList)
                .model(model)
                .build();

        return webClient.post()
                .uri("https://chat.zju.edu.cn/api/ai/v1/chat/completions")
                .header("Authorization", "Bearer " + apiKey)
                .bodyValue(build)
                .retrieve()
                .bodyToFlux(String.class)
                .map(data -> {
//                                            System.out.println(data);
                    if (StringUtils.isEmpty(data) || ("[DONE]").equals(data)) return "";
                    try {
                        String s = "";

                        JSONArray choices = new JSONObject(data)
                                .getJSONArray("choices");
                        Iterable<JSONObject> jsonObjects = choices.jsonIter();
                        while (jsonObjects.iterator().hasNext()) {
                            JSONObject jsonObject = jsonObjects.iterator().next();
                            String finish_reason = jsonObject.get("finish_reason", String.class);
                            if(!StringUtils.isEmpty(finish_reason)){return "";}
                            s+=jsonObject
                                    .getJSONObject("delta")
                                    .get("content", String.class);

                        }
                        return s;
                    } catch (Exception e) {
                        return "";
                    }
                });

    }
}
